package com.sskj.mine.ui.activity;


import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.lzy.okgo.OkGo;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.AppToastInnerCheckUtil;
import com.sskj.mine.R;
import com.sskj.mine.R2;
import com.sskj.mine.bean.PayWayBean;
import com.sskj.mine.bean.PersonCenterItemBean;
import com.sskj.mine.component.DaggerUserDataComponent;
import com.sskj.mine.presenter.SecurityCenterActivityPresenter;
import com.sskj.mine.util.HideUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;

@Route(path = RConfig.MINE_SECURITY_CENTER)//安全中心
public class SecurityCenterActivity extends BaseActivity<SecurityCenterActivityPresenter> {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.recyclerViewPayType)
    RecyclerView recyclerViewPayType;
    @BindView(R2.id.tvAddPayType)
    TextView tvAddPayType;
    @BindView(R2.id.shopContent)
    TextView shopContent;
    @Inject
    UserViewModel userViewModel;
    @BindView(R2.id.chrome_verification)
    RelativeLayout chromeVerification;
    @BindView(R2.id.shop_verification)
    RelativeLayout shopVerification;
    @BindView(R2.id.chromeContent)
    TextView chromeContent;
    private UserData userData;
    private SlimAdapter<PersonCenterItemBean> slimAdapter;
    private MaterialDialog tip;
    private SlimAdapter slimAdapterPayType;
    private TextView chromeSendCode;
    DisposableSubscriber disposableSubscriber;

    @Override
    protected int getLayoutResId() {
        return R.layout.mine_activity_security_center;
    }

    @Override
    public SecurityCenterActivityPresenter getPresenter() {
        return new SecurityCenterActivityPresenter();
    }

    @Override
    protected void initView() {
        setTitle(App.INSTANCE.getString(R.string.mineSecurityCenterActivity0));
        DaggerUserDataComponent.create().inject(this);
        initRecy();
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                OkGo.getInstance().getCommonHeaders().put(SPConfig.ACCOUNT, users.get(0).getAccount());
                OkGo.getInstance().getCommonParams().put(SPConfig.ACCOUNT, users.get(0).getAccount());
                OkGo.getInstance().getCommonHeaders().put(SPConfig.MOBILE, users.get(0).getTel());
                OkGo.getInstance().getCommonParams().put(SPConfig.MOBILE, users.get(0).getTel());
            } else {
                userData = null;
            }
            updateUI();
        });
        ClickUtil.click(tvAddPayType, () -> {
            if (userData == null) {
                return;
            }
            if (AppToastInnerCheckUtil.checkTradePwd(this, userData)) {
                ARouter.getInstance().build(RConfig.MINE_PAY_TYPE_UPDATE).withBoolean(Constans.IS_ADD, true).navigation();
            }
        });
        ClickUtil.click(chromeVerification, () -> {  // 谷歌认证
            if (!userData.isGoogleAuthentication()) {
                ARouter.getInstance().build(RConfig.MINE_CHROME_VERIFICATION).navigation();
            } else {
                if (userData.isGoogleOpenClose()) {  // 谷歌认证开启
                    showBottomDialogClose();
                } else {
                    showBottomDialogOpen();
                }
            }
        });
        ClickUtil.click(shopVerification, () -> {  // 商家认证
            if (AppToastInnerCheckUtil.checkTradePwd(this, userData)) {
                if (userData.isShop()) {
                    ARouter.getInstance().build(RConfig.MINE_SHOP_SUCCESS).navigation();
                } else {
                    if (AppToastInnerCheckUtil.checkPayType(SecurityCenterActivity.this, userData)) {
                        ARouter.getInstance().build(RConfig.MINE_APPLY_SHOP).navigation();
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {
        userViewModel.update();
        mPresenter.getPayType();
    }

    @Override
    protected void onResume() {
        if (mPresenter != null) {
            mPresenter.getPayType();
        }
        super.onResume();
    }

    private void initRecy() {
        HashMap<String, String> payMapName = new HashMap<>();
        payMapName.put("1", getString(R.string.mine_wechat));
        payMapName.put("2", getString(R.string.mine_alipay));
        payMapName.put("3", getString(R.string.mine_bank));
        HashMap<String, Integer> payMapIcon = new HashMap<>();
        payMapIcon.put("1", R.mipmap.mine_icon_pay_type_weixin);
        payMapIcon.put("2", R.mipmap.mine_icon_pay_type_alipay);
        payMapIcon.put("3", R.mipmap.mine_icon_pay_type_bank);
        ArrayList<PersonCenterItemBean> itemBeans = new ArrayList<>();
        itemBeans.add(new PersonCenterItemBean(App.INSTANCE.getString(R.string.mineSecurityCenterActivity1), App.INSTANCE.getString(R.string.mineSecurityCenterActivity8)));
        itemBeans.add(new PersonCenterItemBean(App.INSTANCE.getString(R.string.mineSecurityCenterActivity3), App.INSTANCE.getString(R.string.mineSecurityCenterActivity8)));
        itemBeans.add(new PersonCenterItemBean(App.INSTANCE.getString(R.string.mineSecurityCenterActivity5), App.INSTANCE.getString(R.string.mineSecurityCenterActivity6)));
        itemBeans.add(new PersonCenterItemBean(App.INSTANCE.getString(R.string.mineSecurityCenterActivity7), App.INSTANCE.getString(R.string.mineSecurityCenterActivity8)));
//        itemBeans.add(new PersonCenterItemBean(App.INSTANCE.getString(R.string.mineSecurityCenterActivity9), App.INSTANCE.getString(R.string.mineSecurityCenterActivity10)));
//        itemBeans.add(new PersonCenterItemBean(getString(R.string.mine_shop_auth), App.INSTANCE.getString(R.string.mineSecurityCenterActivity10)));
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(this)
                .setFirstDraw(false)
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.mine_E6E6E6))
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 2)));
        slimAdapter = SlimAdapter.create().register(R.layout.mine_recy_item_security_center, new SlimInjector<PersonCenterItemBean>() {
            @Override
            public void onInject(PersonCenterItemBean data, IViewInjector injector, List payloads) {
                injector
                        .text(R.id.tvTitle, data.getTitle())
                        .text(R.id.tvContent, data.getContent());
            }
        }).attachTo(recyclerView).updateData(itemBeans);
        recyclerViewPayType.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterPayType = SlimAdapter.create().register(R.layout.mine_security_center_pay_type_item, new SlimInjector<PayWayBean>() {
            @Override
            public void onInject(PayWayBean data, IViewInjector injector, List payloads) {
                injector
                        .image(R.id.ivPayType, payMapIcon.get(data.getPayType()))
                        .text(R.id.tvPayType, payMapName.get(data.getPayType()))
//                        .text(R.id.tvPayName, payMapName.get(data.getPayType()))
                        .checked(R.id.checkBox, !data.isDisable())
//                        .with(R.id.tvAccount, view -> {
//                            TextView tvAccount = (TextView) view;
//                            switch (data.getPayType()) {
//                                case "1":
//                                    tvAccount.setText(data.getWxAccount());
//                                    break;
//                                case "2":
//                                    tvAccount.setText(data.getAlipayAccount());
//                                    break;
//                                case "3":
//                                    tvAccount.setText(data.getBankCardNo());
//                                    break;
//                            }
//                        })
                        .clicked(R.id.tvChange, (v) -> {
                            ARouter.getInstance().build(RConfig.MINE_PAY_TYPE_UPDATE)
                                    .withBoolean(Constans.IS_ADD, false)
                                    .withString(Constans.PAY_ID, data.getId())
                                    .withInt(Constans.INIT_POS, Integer.valueOf(data.getPayType()) - 1)
                                    .navigation();
                        })
                        .clicked(R.id.checkBox, (v) -> {
                            mPresenter.togglePay(data.getId(), !data.isDisable());
                        });
            }
        }).attachTo(recyclerViewPayType).updateData(new ArrayList());
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener((recyclerView1, position, v) -> {
                    if (userData == null) {
                        userViewModel.update();
                        return;
                    }
                    switch (position) {
                        case 0://手机
                            if (TextUtils.isEmpty(userData.getTel())) {
                                ARouter.getInstance().build(RConfig.MINE_BIND_MOBILE).navigation();  // 绑定手机号
                            } else {
                                ARouter.getInstance().build(RConfig.MINE_UNBIND_MOBILE).withString("userTel", userData.getTel()).navigation();  // 解除绑定手机号
                            }
                            break;
                        case 1://邮箱
                            if (TextUtils.isEmpty(userData.getEmail())) {
                                ARouter.getInstance().build(RConfig.MINE_BIND_EMAIL).navigation();
                            } else {
                                ARouter.getInstance().build(RConfig.MINE_UNBIND_EMAIL).withString("userEmial", userData.getEmail()).navigation();
                            }
                            break;
                        case 2://登录密码
                            ARouter.getInstance().build(RConfig.MINE_PWD_CHANGE).navigation();
                            break;
                        case 3://支付密码
                            if (AppToastInnerCheckUtil.checkAuth(SecurityCenterActivity.this, userData)) {
                                ARouter.getInstance().build(RConfig.MINE_SET_PAY_PWD).navigation();
                            }
                            break;
                    }
                });
    }


    private void updateUI() {
        if (userData == null) {
            return;
        }
        if (TextUtils.isEmpty(userData.getTel())) {
            slimAdapter.getData().get(0).setContent(App.INSTANCE.getString(R.string.mineSecurityCenterActivity8));
        } else {
            slimAdapter.getData().get(0).setContent("已开启");
        }
        if (TextUtils.isEmpty(userData.getEmail())) {
            slimAdapter.getData().get(1).setContent(App.INSTANCE.getString(R.string.mineSecurityCenterActivity8));
        } else {
            slimAdapter.getData().get(1).setContent(userData.getEmail());
        }
        if (TextUtils.isEmpty(userData.getTradePwd())) {
            slimAdapter.getData().get(3).setContent(App.INSTANCE.getString(R.string.mineSecurityCenterActivity8));
        } else {
            slimAdapter.getData().get(3).setContent(App.INSTANCE.getString(R.string.mineSecurityCenterActivity6));
        }
        if (!userData.isGoogleAuthentication()) {
            chromeContent.setText("未认证");
        } else {
            if (userData.isGoogleOpenClose()) {
                chromeContent.setText("已开启");
            } else {
                chromeContent.setText("已关闭");
            }
        }
        if (userData.isShop()) {    // 商家认证
            shopContent.setText("已认证");
        } else {
            shopContent.setText(App.INSTANCE.getString(R.string.mineSecurityCenterActivity10));
        }
        slimAdapter.notifyItemRangeChanged(0, 4);


    }

    public void setPayType(List<PayWayBean> payWayBeans) {
        if (payWayBeans.size() >= 3) {
            tvAddPayType.setVisibility(View.GONE);
        } else {
            tvAddPayType.setVisibility(View.VISIBLE);
        }
        slimAdapterPayType.updateData(payWayBeans);
    }

    public void toggleShopSuccess() {
        userViewModel.update();
    }

    public void togglePayTypeSuccess() {
        userViewModel.update();
        mPresenter.getPayType();
    }

    @Override
    public boolean getImmersion() {
        return false;
    }

    private void showBottomDialogClose() {
        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(mActivity);
        View inflate = LayoutInflater.from(mActivity).inflate(R.layout.mine_bottom_dialog_chrome, null);
        TextView chromeTitle = inflate.findViewById(R.id.chrome_title);
        chromeTitle.setText("关闭谷歌验证");
        EditText chromeNum = inflate.findViewById(R.id.chrome_num);
        EditText chromeTelCode = inflate.findViewById(R.id.chrome_tel_code);
        chromeSendCode = inflate.findViewById(R.id.chrome_send_code);
        ClickUtil.click(chromeSendCode, () -> {
            chromeSendCode.setEnabled(false);
            mPresenter.sendCode(userData.getTel());
        });
        Button btSubmit = inflate.findViewById(R.id.btSubmit);

        ClickUtil.click(btSubmit, () -> {
            bottomSheetDialog.hide();
            String googleCode = chromeNum.getText().toString();
            String telCode = chromeTelCode.getText().toString();
            if (TextUtils.isEmpty(googleCode)) {
                ToastUtil.showShort("请输入您的谷歌验证码");
                return;
            }
            if (TextUtils.isEmpty(telCode)) {
                ToastUtil.showShort("请输入您的短信验证码");
                return;
            }
            mPresenter.closeGoogle(SPUtil.get(SPConfig.ID, ""), googleCode, telCode);
        });
        bottomSheetDialog.setContentView(inflate);
        bottomSheetDialog.getWindow().findViewById(R.id.design_bottom_sheet)
                .setBackgroundResource(android.R.color.transparent);
        bottomSheetDialog.show();
    }

    private void showBottomDialogOpen() {
        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(mActivity);
        View inflate = LayoutInflater.from(mActivity).inflate(R.layout.mine_bottom_dialog_chrome_open, null);
        TextView chromeTitle = inflate.findViewById(R.id.chrome_title);
        chromeTitle.setText("开启谷歌验证");
        EditText chromeNum = inflate.findViewById(R.id.chrome_num);
        Button btSubmit = inflate.findViewById(R.id.btSubmit);

        ClickUtil.click(btSubmit, () -> {
            bottomSheetDialog.hide();
            String googleCode = chromeNum.getText().toString();
            if (TextUtils.isEmpty(googleCode)) {
                ToastUtil.showShort("请输入您的谷歌验证码");
                return;
            }
            mPresenter.openGoogle(SPUtil.get(SPConfig.ID, ""), googleCode);
        });
        bottomSheetDialog.setContentView(inflate);
        bottomSheetDialog.getWindow().findViewById(R.id.design_bottom_sheet)
                .setBackgroundResource(android.R.color.transparent);
        bottomSheetDialog.show();
    }

    /**
     * 获取验证码倒计时
     */
    public void startCount() {
        DisposUtil.close(disposableSubscriber);
        disposableSubscriber = new DisposableSubscriber<Long>() {
            @Override
            public void onNext(Long aLong) {
                int time = (int) (60 - aLong);
                chromeSendCode.setText(String.format(App.INSTANCE.getString(R.string.mineRegisterActivity8), time));
            }

            @Override
            public void onError(Throwable t) {
                System.out.println(t.toString());
            }

            @Override
            public void onComplete() {
                chromeSendCode.setText(App.INSTANCE.getString(R.string.mineRegisterActivity9));
                chromeSendCode.setEnabled(true);
                if (!disposableSubscriber.isDisposed()) {
                    disposableSubscriber.dispose();
                    disposableSubscriber = null;
                }

            }
        };
        Flowable.interval(0, 1, TimeUnit.SECONDS, Schedulers.newThread())
                .take(60)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableSubscriber);
    }

    public void sendCodeOk() {
        startCount();
    }

    public void sendCodeError() {
        chromeSendCode.setEnabled(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DisposUtil.close(disposableSubscriber);
    }

}
